package src.main.xiangyuan;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class xiangyuanmoshi {
    public static void main(String[] args) {
        BikeSharing bikeSharing = FlyweightFactory.getFlyweightFactory().getBike();
        bikeSharing.use("张三");
        bikeSharing.getStatus();

        BikeSharing bikeSharing1 = FlyweightFactory.getFlyweightFactory().getBike();
        bikeSharing1.use("李四");

        BikeSharing bikeSharing2 = FlyweightFactory.getFlyweightFactory().getBike();
        bikeSharing2.use("王五");

        BikeSharing bikeSharing3 = FlyweightFactory.getFlyweightFactory().getBike();
        bikeSharing3.use("赵六");

        BikeSharing bikeSharing4 = FlyweightFactory.getFlyweightFactory().getBike();
        bikeSharing4.use("田一");

        BikeSharing bikeSharing5 = FlyweightFactory.getFlyweightFactory().getBike();
        if (bikeSharing5 == null) {
            System.out.println("当前没有车可以使用!");
        }
        System.out.println("=======================");
        // 赵六还车
        bikeSharing3.back();
        BikeSharing bikeSharing6 = FlyweightFactory.getFlyweightFactory().getBike();
        bikeSharing6.use("五二");

    }
}

/**
 * 共享单车抽象类（一个具体类型，可只有实体类）
 */
abstract class BikeSharing {
    // 共享单车当前状态 0为未被使用 1为被使用
    protected Integer status = 0;

    // 共享单车使用方法 改变内部状态 0->1
    abstract void use(String user);

    // 共享单车还车方法 改变内部状态 1->0
    abstract void back();

    public void getStatus() {
        System.out.println("当前单车使用状态:" + (this.status == 1 ? "使用中" : "未使用"));
    }
}

class HaLuoBike extends BikeSharing {
    private String bikeId;
    private String user;

    // 构造方法
    public HaLuoBike(String bikeId) {
        this.bikeId = bikeId;
    }

    // 改变使用状态
    @Override
    void use(String user) {
        this.user=user;
        status = 1;
        System.out.println("单车编号" + this.bikeId + "正在被用户" + this.user + "使用!");
    }

    // 还车方法
    @Override
    void back() {
        status = 0;
        System.out.println(this.user+"还车成功!");
    }
}


class FlyweightFactory {
    // 创建工厂单例
    private static FlyweightFactory flyweightFactory = new FlyweightFactory();

    // 创建共享单车集合
    private Map<String, BikeSharing> bikeMap = new ConcurrentHashMap<>();

    // 工厂创建单车数量控制属性
    private Integer bikeSum = 5;

    // 构造方法 创建单车
    private FlyweightFactory() {
        for (int i = 0; i < this.bikeSum; i++) {
            this.bikeMap.put(String.valueOf(i + 1), new HaLuoBike(String.valueOf(i + 1)));
        }
    }

    // 工厂get方法
    public static FlyweightFactory getFlyweightFactory() {
        return flyweightFactory;
    }

    // 返回共享单车对象
    public BikeSharing getBike() {
        for (int i = 0; i < this.bikeMap.size(); i++) {
            if (this.bikeMap.get(String.valueOf(i + 1)).status == 0) {
                System.out.println("可用单车编号："+(i + 1));
                return this.bikeMap.get(String.valueOf(i + 1));
            }
        }
        return null;
    }

}

